<template>
  <div class="page-content">
    <MenuBar v-if="!isMobile" passTab="999" />

    <PhoneMenuBar v-else passTab="999" />

    <div style="height: 70px;"></div>

    <div :style="{ 'padding': isMobile ? '5px 12px' : '5px 120px' }" class="breadcrumb-bar">

      <n-breadcrumb separator=">">
        <n-breadcrumb-item>
          <RouterLink to="/">
            <n-icon size="16" color="#999999">
              <Home />
            </n-icon>首页

          </RouterLink>

        </n-breadcrumb-item>
        <n-breadcrumb-item>
          搜索结果列表
        </n-breadcrumb-item>
      </n-breadcrumb>
    </div>

    <div class="page-product">
      <div class="product-title">搜索结果如下：</div>

      <div class="search-result">当前搜索关键词

        <n-input v-model:value="searchValue" placeholder="请输入关键词" autosize
          :style="{ 'min-width': isMobile ? '50%' : '20%' }" clearable />

        <n-button quaternary @click="getNewsList()">
          搜索
        </n-button>
      </div>

      <div class="search-result" style="margin-top: 5px;">找到{{ totalCount }}条结果</div>


      <div class="message-layout">

        <n-list bordered show-divider size="large" clickable hoverable>
          <n-list-item v-for="(item) in all_newsList" v-bind:key="item.id">

            <n-thing>
              <template #header>

                <div style="display: flex;align-items: center;">
                  <h3 style="font-size: 18px; margin: 0; font-weight: bold;">{{ item.title }}</h3>
                </div>


              </template>
              <template #description>
                <n-space size="large">
                  <n-tag :bordered="false" type="info" size="large">
                    {{ item.addtime.length > 10 ? item.addtime.substring(0, 10) : item.addtime }}
                  </n-tag>
                </n-space>
              </template>
              <div class="message-content">{{ item.description }}</div>
              <div style="display: flex;justify-content: end;margin-top: 5px;" v-if="isMobile">
                <n-button @click="downloadFile(item)" type="info">
                  查看详情
                  <n-icon>
                    <img src="@/assets/images/png/了解更多.png" style="width: 12px;margin-left: 5px;" />
                  </n-icon></n-button>
              </div>
            </n-thing>
            <template #suffix v-if="!isMobile">
              <n-button @click="downloadFile(item)" type="info" style="margin-right:30px">
                查看详情
                <n-icon>
                  <img src="@/assets/images/png/了解更多.png" style="width: 12px;margin-left: 5px;" />
                </n-icon></n-button>
            </template>
          </n-list-item>
        </n-list>

      </div>


      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange1" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>

          <div v-else style="display: flex;justify-content: space-between;align-items: center;margin-top: 15px;">

        <n-button type="info" @click="pageNumOnClick('-')" :style="{ visibility: pageNum != 1 ? 'visible' : 'hidden' }">
          上一页
        </n-button>

        <div style="width: 80px;"><n-select v-model:value="pageNum" @update:value="handlePageNumValue"
            :options="pageNumOptions" filterable /></div>

        <n-button type="info" @click="pageNumOnClick('+')" :style="{ visibility: pageNum != totalNum ? 'visible' : 'hidden' }">
          下一页
        </n-button>
      </div>

    </div>

    <BottomBar />
  </div>
</template>

<script setup name="productListPage">
import { API_URL } from '@/config'
import { Home } from '@vicons/ionicons5'
import { searchList } from '@/api'
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import MenuBar from '@/components/MenuBar.vue'
import PhoneMenuBar from '@/components/PhoneMenuBar.vue'
import BottomBar from '@/components/BottomBar.vue'
// 创建一个响应式变量来存储是否为移动设备
const isMobile = ref(false);

// 定义一个函数来检查用户代理
const checkDevice = () => {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // 设置isMobile的值
  isMobile.value = /android/i.test(userAgent) || /iPhone|iPad|iPod/i.test(userAgent);
};



const searchValue = ref("")


const all_newsList = ref([])
const totalNum = ref(0)
const totalCount = ref(0)
const pageSize = 10
const getNewsList = async () => {
  if (searchValue.value == "") {
    all_newsList.value = []

    totalCount.value = 0;
    totalNum.value = 0;
    return
  }
  const params = {
    page: pageNum.value,
    size: pageSize,
    searchword: searchValue.value
  }
  const result = await searchList(params)

  console.log("newsList", result)

  if (result != null && result.data != null) {

    all_newsList.value = result.data

    totalCount.value = result.total;

    const fullPages = Math.floor(result.total / pageSize); // 完整页数
    const remainder = result.total % pageSize;             // 余数

    totalNum.value = remainder > 0 ? fullPages + 1 : fullPages;

      pageNumOptions.value = []
    for (let i = 1; i <= totalNum.value; i++) {
      pageNumOptions.value.push({ label: i + "", value: i + "" })
    }

  }
}
const route = useRoute()
const router = useRouter()
const downloadFile = (item) => {
  console.log("downloadFile", item.module)


  if (item.module == 3) {
    router.push({
      name: 'PInfo',
      query: {
        productId: item.id,
        fromSearch: true,
      }
    })
  } else if (item.module == 2) {
    router.push({
      name: 'NewsDetail',
      query: {
        advanceId: item.id,
        fromSearch: true,
      }
    })
  } else {
    router.push({
      name: 'AdvanceDetail',
      query: {
        advanceId: item.id,
        fromSearch: true,
      }
    })
  }

}



onMounted(async () => {
  checkDevice();

  searchValue.value = route.query.searchValue || ""

  getNewsList()
});
const pageNum = ref(1)
// const chooseCategory = async (categoryId) => {
//   // console.log("chooseCategory", categoryId)
//   typeId.value = categoryId;
//   pageNum.value = 1;
//   getNewsList()
// }

const handlePageChange = (page) => {
  console.log('当前页:', page)
  getNewsList()
}

const handlePageChange1 = (page) => {
  console.log('当前页:', page)
  getNewsList()

  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // 平滑滚动
  });
}

// watch(
//   () => route.query.typeId,
//   (newId) => {
//     typeId.value = newId || -1
//     console.log("typeId.value", typeId.value)
//     if (typeId.value != -1)
//       getNewsList()
//   },
//   { immediate: true }
// )

// 自定义分页主题样式
const paginationThemeOverrides = {

  // 👇 这些是官方支持的 overrides 属性
  itemColor: '#ffffff',                    // 默认背景
  itemColorHover: '#f0f0f0',               // 悬停背景
  itemColorActive: '#00aeff',              // 选中背景（蓝色）
  itemColorActiveHover: '#00aeff',         // 选中悬停
  textColor: '#333333',                    // 默认文字
  textColorActive: '#ffffff',              // ✅ 选中文字颜色（白色）
  itemBorder: '1px solid #d9d9d9',         // 边框
  itemBorderHover: '1px solid #00aeff',    // 悬停边框
  itemBorderActive: '1px solid #00aeff',   // 选中边框

}

const pageNumOptions = ref([])

function pageNumOnClick(type) {

  if (type == "+") {
    pageNum.value++;
  } else {
    pageNum.value--;
  }

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}

function handlePageNumValue(e) {
  console.log("handlePageNumValue", pageNum.value)

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}

</script>

<style scoped lang="scss">
/* 容器样式 */
.page-content {
  width: 100vw;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  .breadcrumb-bar {
    background: #eeeeee;
    display: flex;
    align-items: center;
  }


  @media (min-width: 769px) {
    .page-product {
      padding: 15px 120px;
      flex: 1;

      .search-result {
        color: #111111;
        font-size: 14px;
      }

      .product-title {
        color: #111111;
        font-size: 30px;
        font-weight: bold;
        line-height: 140%;
        margin-bottom: 15px;
      }



      .message-layout {
        margin-top: 15px;
        background: white;
        padding: 50px;

        .message-content {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          /* 可省略，-webkit-line-clamp 会处理 */
          word-break: break-word;
          max-width: 100%;
          min-height: 40px;
        }

      }

    }
  }

  /* 手机端样式 */
  @media (max-width: 768px) {
    .page-product {
      padding: 15px;

      .search-result {
        color: #111111;
        font-size: 14px;
      }

      .product-title {
        color: #111111;
        font-size: 18px;
        font-weight: bold;
        // margin-bottom: 15px;
      }

      .message-layout {
        margin-top: 15px;
        background: white;
        padding: 5px;

        .message-content {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          /* 可省略，-webkit-line-clamp 会处理 */
          word-break: break-word;
          max-width: 100%;
          min-height: 40px;
        }

      }
    }
  }

  :deep(.n-input__state-border) {
    --n-border-hover: 1px solid #00aeff !important;
    --n-border-focus: 1px solid #00aeff !important;
  }

  :deep(.n-pagination) {
    /* 强制重置所有 Pagination 相关变量 */
    --n-item-text-color-active: #ffffff !important;
    /* ✅ 关键：白色 */
    --n-item-text-color-hover: #333333 !important;
  }

}
</style>